// 连接数据库
let mysql = require('mysql')

module.exports = {
  db: null,
  cfg: {
    host: 'localhost',
    user: 'root',
    password: 'ALD-mysql@2016',
    database: 'stationdata'
  },
  open: function () {
    this.db = mysql.createConnection(this.cfg)
    this.db.connect(this.handleError)
    this.db.on('error', this.handleError)
  },
  close: function () {
    this.db.end()
  },
  query: function (sql) {
    return new Promise((resolve, reject) => {
      this.db.query(sql, function (err, rows, fields) {
        if (err) {
          reject(err)
        } else {
          resolve(rows)
        }
      })
    })
  },
  handleError: function (err) {
    if (err) {
      // 如果是连接断开，自动重新连接
      if (err.code === 'PROTOCOL_CONNECTION_LOST') {
        this.init()
      } else {
        console.error(err.stack || err)
      }
    }
  }
}
